<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input v-model.trim="arr.uname" type="text" />
    </div>
    <div>
      <span>年龄:</span>
      <input v-model.trim="arr.age" type="number" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="arr.sex">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="addArr">添加/修改</button>
    </div>
    <div>
      <table
        border="1"
        cellpadding="10"
        cellspacing="0"
      >
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="obj,index in list" :key="index">
          <td>{{ index + 1 }}</td>
          <td>{{ obj.uname }}</td>
          <td>{{ obj.age }}</td>
          <td>{{ obj.sex }}</td>
          <td>
            <button @click="deleteArr(index)">删除</button>
            <button @click="bianArr(index)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data () {
    return {
      re: false,
      res: '',
      arr: {
        uname: '',
        age: '',
        sex: ''
      },
      list: [
        { uname: 'Tom', age: 20, sex: '男' },
        { uname: 'Jone', age: 20, sex: '男' },
        { uname: 'Tuoni', age: 20, sex: '女' }
      ]
    }
  },
  methods: {
    addArr () {
      if (!this.arr.uname || !this.arr.age || !this.arr.sex) {
        return alert('必填项不能为空')
      }
      const id = this.list.length === 0 ? 0 : this.list[this.list.length - 1].id + 1
      if (!this.re) {
        this.list.push({
          id: id,
          ...this.arr
        })
      } else {
        this.list[this.res] = { ...this.arr }
      }
      this.arr.uname = this.arr.age = ''
    },
    deleteArr (i) {
      if (confirm('确定删除吗?')) {
        this.list.splice(i, 1)
      }
    },
    bianArr (i) {
      this.arr.uname = this.list[i].uname
      this.arr.age = this.list[i].age
      this.arr.sex = this.list[i].sex
      this.re = true
      this.res = i
    }
  }
}
</script>
